package com.gitee.wsl.collections.internal

import com.gitee.wsl.text.format.format
import kotlin.jvm.JvmOverloads


/**
 * Static convenience methods that help a method or constructor check whether it was invoked
 * correctly (that is, whether its *preconditions* were met).
 *
 *
 * If the precondition is not met, the `Preconditions` method throws an unchecked exception
 * of a specified type, which helps the method in which the exception was thrown communicate that
 * its caller has made a mistake. This allows constructs such as
 *
 * <pre>`public static double sqrt(double value) {
 * if (value < 0) {
 * throw new IllegalArgumentException("input is negative: " + value);
 * }
 * // calculate square root
 * }
`</pre> *
 *
 *
 * to be replaced with the more compact
 *
 * <pre>`public static double sqrt(double value) {
 * checkArgument(value >= 0, "input is negative: %s", value);
 * // calculate square root
 * }
`</pre> *
 *
 *
 * so that a hypothetical bad caller of this method, such as:
 *
 * <pre>`void exampleBadCaller() {
 * double d = sqrt(-1.0);
 * }
`</pre> *
 *
 *
 * would be flagged as having called `sqrt()` with an illegal argument.
 *
 * <h3>Performance</h3>
 *
 *
 * Avoid passing message arguments that are expensive to compute; your code will always compute
 * them, even though they usually won't be needed. If you have such arguments, use the conventional
 * if/throw idiom instead.
 *
 *
 * Depending on your message arguments, memory may be allocated for boxing and varargs array
 * creation. However, the methods of this class have a large number of overloads that prevent such
 * allocations in many common cases.
 *
 *
 * The message string is not formatted unless the exception will be thrown, so the cost of the
 * string formatting itself should not be a concern.
 *
 *
 * As with any performance concerns, you should consider profiling your code (in a production
 * environment if possible) before spending a lot of effort on tweaking a particular element.
 *
 * <h3>Other types of preconditions</h3>
 *
 *
 * Not every type of precondition failure is supported by these methods. Continue to throw
 * standard JDK exceptions such as [java.util.NoSuchElementException] or [ ] in the situations they are intended for.
 *
 * <h3>Non-preconditions</h3>
 *
 *
 * It is of course possible to use the methods of this class to check for invalid conditions
 * which are *not the caller's fault*. Doing so is **not recommended** because it is
 * misleading to future readers of the code and of stack traces. See [Conditional failures
 * explained](https://github.com/google/guava/wiki/ConditionalFailuresExplained) in the Guava User Guide for more advice. Notably, [Verify] offers assertions
 * similar to those in this class for non-precondition checks.
 *
 * <h3>`java.util.Objects.requireNonNull()`</h3>
 *
 *
 * Projects which use `com.google.common` should generally avoid the use of [ ][java.util.Objects.requireNonNull]. Instead, use whichever of [ ][.checkNotNull] or [Verify.verifyNotNull] is appropriate to the situation.
 * (The same goes for the message-accepting overloads.)
 *
 * <h3>Only `%s` is supported</h3>
 *
 *
 * `Preconditions` uses [String.format] to format error message template
 * strings. This only supports the `"%s"` specifier, not the full range of [ ] specifiers. However, note that if the number of arguments does not match the
 * number of occurrences of `"%s"` in the format string, `Preconditions` will still
 * behave as expected, and will still include all argument values in the error message; the message
 * will simply not be formatted exactly as intended.
 *
 * <h3>More information</h3>
 *
 *
 * See the Guava User Guide on [using `Preconditions`](https://github.com/google/guava/wiki/PreconditionsExplained).
 *
 * @author Kevin Bourrillion
 * @since 2.0
 */
object Preconditions {
    /**
     * Ensures the truth of an expression involving one or more parameters to the calling method.
     *
     * @param expression a boolean expression
     * @throws IllegalArgumentException if `expression` is false
     */
    fun checkArgument(expression: Boolean) {
        require(expression)

    }

    /**
     * Ensures the truth of an expression involving one or more parameters to the calling method.
     *
     * @param expression a boolean expression
     * @param errorMessage the exception message to use if the check fails; will be converted to a
     * string using [String.valueOf]
     * @throws IllegalArgumentException if `expression` is false
     */
    fun checkArgument(expression: Boolean, errorMessage: Any?) {
        require(expression) { errorMessage.toString() }
    }

    /**
     * Ensures that an object reference passed as a parameter to the calling method is not null.
     *
     * @param reference an object reference
     * @return the non-null reference that was validated
     * @throws NullPointerException if `reference` is null
     * @see Verify.verifyNotNull Verify.verifyNotNull
     */
    fun <T> checkNotNull(reference: T?): T? {
        if (reference == null) {
            throw NullPointerException()
        }
        return reference
    }

    /**
     * Ensures that `index` specifies a valid *element* in an array, list or string of size
     * `size`. An element index may range from zero, inclusive, to `size`, exclusive.
     *
     * @param index a user-supplied index identifying an element of an array, list or string
     * @param size the size of that array, list or string
     * @param desc the text to use to describe this index in an error message
     * @return the value of `index`
     * @throws IndexOutOfBoundsException if `index` is negative or is not less than `size`
     * @throws IllegalArgumentException if `size` is negative
     */
    /**
     * Ensures that `index` specifies a valid *element* in an array, list or string of size
     * `size`. An element index may range from zero, inclusive, to `size`, exclusive.
     *
     * @param index a user-supplied index identifying an element of an array, list or string
     * @param size the size of that array, list or string
     * @return the value of `index`
     * @throws IndexOutOfBoundsException if `index` is negative or is not less than `size`
     * @throws IllegalArgumentException if `size` is negative
     */
    @JvmOverloads
    fun checkElementIndex(index: Int, size: Int, desc: String? = "index"): Int {
        // Carefully optimized for execution by hotspot (explanatory comment above)
        if (index < 0 || index >= size) {
            throw IndexOutOfBoundsException(badElementIndex(index, size, desc))
        }
        return index
    }

    private fun badElementIndex(index: Int, size: Int, desc: String?): String {
        if (index < 0) {
            return String.format("%s (%s) must not be negative", desc, index)
        } else require(size >= 0) { "negative size: $size" }
        // index >= size
        return String.format("%s (%s) must be less than size (%s)", desc, index, size)
    }

    /**
     * Ensures that `start` and `end` specify valid *positions* in an array, list or
     * string of size `size`, and are in order. A position index may range from zero to `size`, inclusive.
     *
     * @param start a user-supplied index identifying a starting position in an array, list or string
     * @param end a user-supplied index identifying an ending position in an array, list or string
     * @param size the size of that array, list or string
     * @throws IndexOutOfBoundsException if either index is negative or is greater than `size`,
     * or if `end` is less than `start`
     * @throws IllegalArgumentException if `size` is negative
     */
    fun checkPositionIndexes(start: Int, end: Int, size: Int) {
        // Carefully optimized for execution by hotspot (explanatory comment above)
        if (start < 0 || end < start || end > size) {
            throw IndexOutOfBoundsException(badPositionIndexes(start, end, size))
        }
    }

    private fun badPositionIndexes(start: Int, end: Int, size: Int): String {
        if (start < 0 || start > size) {
            return badPositionIndex(start, size, "start index")
        }
        if (end < 0 || end > size) {
            return badPositionIndex(end, size, "end index")
        }
        // end < start
        return String.format("end index (%s) must not be less than start index (%s)", end, start)
    }

    private fun badPositionIndex(index: Int, size: Int, desc: String?=null): String {
        if (index < 0) {
            return String.format("%s (%s) must not be negative", desc, index)
        } else require(size >= 0) { "negative size: $size" }
        // index > size
        return String.format("%s (%s) must not be greater than size (%s)", desc, index, size)
    }
}